//
//  ImageRecognizer.swift
//  Health-Doctor
//
//  Created by 勇胡 on 2023/5/26.
//  Copyright © 2023 掌上卫健. All rights reserved.
//单张图片识别器，识别身份证号码  身份证识别
//利用AI  和SDK ocr两种方式识别（增加识别率）

import Foundation
import Vision
import AppKit

class ImageRecognizer: NSObject {
    
    public var patternList:[String] = []
    public var recoginzeFinishBlock: ((_ value:String)->())?
    
    private var request:NSObject?
    public override init() {
        super.init()
        initService()
    }
    
    private func initService(){
        let request = VNRecognizeTextRequest {[weak self] (request, error) in
            guard let `self` = self else { return }
            guard let observations = request.results as? [VNRecognizedTextObservation] else {
                return
            }
            if observations.isEmpty{
                return
            }
            
            for observation in observations{
                guard let candidate = observation.topCandidates(1).first else { continue }
                let content = candidate.string
                print("扫描到=>\(content)")
                for pattern in self.patternList{
                    let value = content.isMatch(pattern: pattern)
                    if value{
                        self.recoginzeFinishBlock?(content)
//                        return
                    }
                }
            }
        }
        request.recognitionLevel = .accurate
        request.recognitionLanguages = ["zh-Hans","en-US"]
        self.request = request
        
    }
    
    public func startScan(image: NSImage){
        guard let img = image.cgImage else{return}
        let requestHandler = VNImageRequestHandler(cgImage: img)
        do {
            if let re = self.request as? VNRecognizeTextRequest{
                try requestHandler.perform([re])
            }
        } catch {
            
        }
    }
}
